package ua.edu.nuos.tees.jdmmon.gui.components;


import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

/**
 * Digital indicator for power indicating
 *
 * @author Olha Mudrievska
 *         12.05.13
 */
public class DigitalIndicator extends JPanel {

    private BufferedImage backgroundImage = null;
    private JLabel digitalIndicator = new JLabel();

    public DigitalIndicator(URL imageUrl){
        setLayout(new GridBagLayout());
        setImage(imageUrl);
        addDigitalIndicator("0");
    }

    private void addDigitalIndicator(String initialText){
        GridBagConstraints gbc = new GridBagConstraints();
        digitalIndicator.setOpaque(true);
        digitalIndicator.setForeground(Color.WHITE);
        digitalIndicator.setBackground(new Color(70, 70, 70));
        digitalIndicator.setHorizontalAlignment(SwingConstants.RIGHT);
        digitalIndicator.setFont(new Font("Arial", Font.BOLD, 20));
        digitalIndicator.setText(initialText);
        gbc.weighty = 1.0;
        gbc.weightx = 1.0;
        gbc.anchor = GridBagConstraints.PAGE_START;
        gbc.insets = new Insets(60,0,0,0);
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(digitalIndicator, gbc);
    }

    /**
     * Set background image
     * @param imageUrl image URL address
     */
    public void setImage(URL imageUrl) {
        try {
            backgroundImage = ImageIO.read(imageUrl);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    /**
     * Set current value
     * @param value value
     */
    public void setValue(long value) {
        digitalIndicator.setText(String.valueOf(value));
    }

    @Override
    public void paintComponent(Graphics g) {
        int xShift = (this.getSize().width - backgroundImage.getWidth()) / 2;
        int yShift = 5;
        super.paintComponent(g);
        g.drawImage(backgroundImage, xShift, yShift, null);
    }
}
